package com.example.lcpharmacy.controller;

import com.example.lcpharmacy.entity.GoodsCategoryEntity;
import com.example.lcpharmacy.entity.UserEntity;
import com.example.lcpharmacy.lcutils.Pagination;
import com.example.lcpharmacy.mapper.UserDao;
import com.example.lcpharmacy.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


@RestController
@RequestMapping("/user")
public class UserImpl {

    @Autowired
    UserDao userDao;

    @Autowired
    HttpServletRequest request;

    @Autowired
    UserService userService;

    @RequestMapping("/login")
    public UserEntity login(@RequestBody UserEntity userEntity){
        System.out.println(userEntity);
        UserEntity usersData = userDao.select(userEntity);
        //((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //可以通过上下文获取request
        HttpSession session = request.getSession(true);
        session.setAttribute("currentUser",usersData);
        return usersData;
    }

    @RequestMapping("/userInfo")
    public UserEntity userInfo(){
        Object currentUser = request.getSession().getAttribute("currentUser");
        return (UserEntity) currentUser;
    }

    @RequestMapping("/register")
    public String register(@RequestBody UserEntity userEntity){
        String result = userService.saveRegister(userEntity);
        return result;
    }

    @RequestMapping("/allUserInfo")
    public PageInfo allUsersInfo(@RequestBody Pagination pagination){
        PageHelper.startPage(pagination.getPageNum(),10);
        List<UserEntity> users = userDao.selectUsers();

        return new PageInfo(users);
    }

    /**
     * 注销用户
     * @return
     */
    @RequestMapping("/deleteUser")
    public int deleteCategory(@RequestBody UserEntity userEntity) {
        int i = userDao.deleteById(userEntity.getId());
        return i;
    }

    /**
     * 更新用户信息
     * @return
     */
    @RequestMapping("/saveUserModify")
    public String saveUserModify(@RequestBody UserEntity userEntity) {
        String message = userService.saveUserModify(userEntity);
        return message;
    }
}
